package sliding_window

import (
	"happy-go/leetcode/kit"
)

/*
You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
*/

func AddTwoNumbers(l1 *kit.ListNode, l2 *kit.ListNode) *kit.ListNode {
	header := &kit.ListNode{Val: 0}
	n1, n2, mod, current := 0, 0, 0, header

	for l1 != nil || l2 != nil || mod != 0 {
		if l1 != nil {
			n1 = l1.Val
			l1 = l1.Next
		} else {
			n1 = 0
		}

		if l2 != nil {
			n2 = l2.Val
			l2 = l2.Next
		} else {
			n2 = 0
		}

		current.Next = &kit.ListNode{Val: (n1 + n2 + mod) % 10}
		current = current.Next
		mod = (n1 + n2 + mod) / 10
	}

	return header.Next
}

func AddTwoNumbers2(l1 *kit.ListNode, l2 *kit.ListNode) *kit.ListNode {
	header := &kit.ListNode{Val: 0}
	current := header
	mod := 0
	for l1 != nil || l2 != nil || mod != 0 {
		val := mod
		if l1 != nil {
			val += l1.Val
			l1 = l1.Next
		}
		if l2 != nil {
			val += l2.Val
			l2 = l2.Next
		}
		current.Next = &kit.ListNode{Val: val % 10}
		current = current.Next
		mod = val / 10
	}
	return header.Next
}
